package net.guoyixian.admin.shiro;

import java.util.Set;

import net.guoyixian.admin.pojo.SysManagers;
import net.guoyixian.admin.service.SysManagersService;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * <p>
 * User: yecheng
 * <p>
 * Date: 16-1-14
 * <p>
 * Version: 1.0
 */
public class UserRealm extends AuthorizingRealm {

	@Autowired
	private SysManagersService sysManagersService;

	/**
	 * 权限验证
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(
			PrincipalCollection principals) {
		String username = (String) principals.getPrimaryPrincipal();
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
		try {
			// 1、获取用户session
			Subject shiroUser = SecurityUtils.getSubject();
			Session session = shiroUser.getSession();
			// 2、查找session中是否有角色、权限
			Set<String> userRoles = (Set<String>) session
					.getAttribute("userRoles");
			Set<String> userPermissions = (Set<String>) session
					.getAttribute("userPermissions");
			// 3、如果没有，则从数据库中查找并写入session中
			if (userRoles == null || userPermissions == null) {
				userRoles = sysManagersService.findRoles(username);
				userPermissions = sysManagersService.findPermissions(username);
				session.setAttribute("userRoles", userRoles);
				session.setAttribute("userPermissions", userPermissions);
			}
			//4、返回角色权限
			authorizationInfo.setRoles(userRoles);
			authorizationInfo.setStringPermissions(userPermissions);

			// 设置角色
//			authorizationInfo.setRoles(sysManagersService.findRoles(username));
//			// 设置权限
//			authorizationInfo.setStringPermissions(sysManagersService
//					.findPermissions(username));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return authorizationInfo;
	}

	/**
	 * 登录验证
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken token) throws AuthenticationException {
		// 1、获得用户名
		String username = (String) token.getPrincipal();
		// 2、通过用户名查找该用户
		SysManagers sysManagers = sysManagersService.queryByUsername(username);
		if (sysManagers == null) {
			throw new UnknownAccountException();// 没找到帐号
		}
		if (sysManagers.getLocked() == 1) {
			throw new LockedAccountException(); // 帐号锁定
		}
		// 3、将用户的id，name写入当前session
		Subject shiroUser = SecurityUtils.getSubject();
		Session session = shiroUser.getSession();
		session.setAttribute("currentUserId", sysManagers.getId());
		session.setAttribute("currentUserName", sysManagers.getUsername());

		// 返回authenticationInfo
		SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
				sysManagers.getUsername(), sysManagers.getPassword(), getName());
		return authenticationInfo;
	}

	@Override
	public void clearCachedAuthorizationInfo(PrincipalCollection principals) {
		super.clearCachedAuthorizationInfo(principals);
	}

	@Override
	public void clearCachedAuthenticationInfo(PrincipalCollection principals) {
		super.clearCachedAuthenticationInfo(principals);
	}

	@Override
	public void clearCache(PrincipalCollection principals) {
		super.clearCache(principals);
	}

	public void clearAllCachedAuthorizationInfo() {
		getAuthorizationCache().clear();
	}

	public void clearAllCachedAuthenticationInfo() {
		getAuthenticationCache().clear();
	}

	public void clearAllCache() {
		clearAllCachedAuthenticationInfo();
		clearAllCachedAuthorizationInfo();
	}

}